package com.kehutong.message.service;

import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import com.kehutong.message.entity.TemplateSetting;
import com.kehutong.message.enums.MiniApiSuffix;
import com.kehutong.message.urlConfig.WebChatUrlConfig;
import com.kehutong.webchat.service.WeChatService;

import java.sql.Timestamp;

/**
 * 小程序消息
 */
@WebService("/message/mini")
public class MiniMessageService {

	private static final Logger logger = LoggerFactory.getLogger(MiniMessageService.class);
	
	@Inject
	private WebChatUrlConfig webChatConfig;
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private WeChatService weChatService;
	@Inject
	private DoveClient doveClient;

	/**
	 * <p>发送微信小程序消息</p>
	 * @param json openid 待发送人openid，data 发送内容，templateType 模板类型， param 小程序路径后拼装参数，key1=value1&key2=value2...
	 * @throws Exception
	 */
	@ReqMapping("/uniformSend")
	public Object uniformSend(JSONObject json) {
		logger.info("MiniMessageService.uniformSend请求消息参数:{}", json.toJSONString());
		if (Objects.isEmpty(json.getString("openid"))){
			String openId = getOpenId(json.getString("uuid"), json.getString("companyNo"));
			if (Objects.isEmpty(openId))
				return Result.error(0, "找不到openid");

			json.put("openid", openId);
		}

		String templateType = json.getString("templateType");
		TemplateSetting template = jdbcSession.findOne(TemplateSetting.class)
											  .eq("templateType", templateType)
											  .eq("deleted", false)
											  .exe();
		if (Objects.isNull(template)) {
			return Result.error(0, "未配置该类型模板");
		}

		JSONObject body = getSendWebChatShareJson(json, template);
		logger.info("MiniMessageService.uniformSend.send请求消息参数:{}", body.toJSONString());
		try {
			String access_token = weChatService.getAccessToken(template.getMiniAppId()); // 对应公众号/小程序的token
			return send(access_token, body, MiniApiSuffix.MSG_TEMPLATE_UNIFORM_SEND);
		} catch (NullPointerException npe) {
			logger.error(npe.getMessage(), npe);
			return Result.error(0, "系统异常");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return Result.error(0, "系统异常");
		}
	}


	private String getOpenId(String uuid, String companyNo){
		JSONObject rs = new JSONObject();
		try {
			rs = doveClient.post("/kht-bin/wechat/getMemberMap", http -> {
				http.addParam("khtId", uuid);
				http.addParam("companyNo",companyNo);
			});
		} catch (Exception e) {
			logger.error("用户ID："+uuid+"请求/kht-bin/wechat/getMemberMap接口异常");
			return null;
		}

		int code = rs.getIntValue("code");
		if (code != 200) {
			logger.warn("失败：" + rs.getString("message"));
			return null;
		}
		JSONObject memberMap = rs.getJSONObject("data");
		if(Objects.isEmpty(memberMap)){
			logger.warn("用户ID：" + uuid + "的用户没有关注过公众号");
			return null;
		}

		String openId = memberMap.getString("mp_open_id");
		if(Objects.isBlank(openId)){
			logger.warn("用户ID：" + uuid+ "的用户openId不存在");
			return null;
		}

		return openId;
	}

	private JSONObject getSendWebChatShareJson(JSONObject json, TemplateSetting template) {
		String pagePath = template.getMiniPagePath();
		String param = json.getString("param");
		if (Objects.nonEmpty(param)) {
			if (pagePath.contains("?")) {
				pagePath += "&" + param;
			} else {
				pagePath += "?" + param;
			}
		}

		JSONObject miniprogram = new JSONObject();
		miniprogram.put("appid", template.getMiniAppId()); // 小程序appId
		miniprogram.put("pagepath", pagePath); // 小程序路径

		JSONObject template_msg = new JSONObject();
		template_msg.put("appid", template.getAppId());// 公众号appid，要求与小程序有绑定且同主体
		template_msg.put("template_id", template.getTemplateNo());// 公众号模板id
		// template_msg.put("url", json.getString("url"));// 公众号模板消息所要跳转的url---感觉用不上...
		template_msg.put("miniprogram", miniprogram);// 公众号模板消息所要跳转的小程序，小程序的必须与公众号具有绑定关系
		Object obj = json.get("data");
		if (obj instanceof String) {
			String d = (String) obj;
			template_msg.put("data", JSONObject.parseObject(d));// 公众号模板消息的数据
		} else {
			template_msg.put("data", json.getJSONObject("data"));// 公众号模板消息的数据
		}

		JSONObject body = new JSONObject();
		body.put("touser", json.getString("openid"));// 用户openid，可以是小程序的openid，也可以是mp_template_msg.appid对应的公众号的openid
		body.put("mp_template_msg", template_msg);

		return body;
	}

	/**
	 * <p>发送http请求</p>
	 *
	 * <p>文档地址：https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html</p>
	 *
	 * @param json body
	 * @param pageSuffix 接口地址后缀
	 * @throws Exception
	 */
	private Object send(String access_token, JSONObject json, MiniApiSuffix pageSuffix) throws Exception {

		if (Objects.isEmpty(access_token)) {
			return Result.error(0, "access_token参数不能为空");
		}

		JSONObject result = webChatConfig.post(pageSuffix.getSuffix(), http -> {
			http.addParam("access_token", access_token);
			http.setBody(json.toJSONString());
		});
		logger.info("MiniMessageService.uniformSend.sendResult：{}", result.toJSONString());
		if (result.getIntValue("errcode") != 0) {
			return Result.error(0, "请求异常!");
		}

		return Result.success();
	}
}
